package cxm.proj.xtalk;

import java.util.ArrayList;
import java.util.List;

import org.jivesoftware.smack.RosterEntry;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.ListView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.TextView;
import android.widget.Toast;
import cxm.lib.util.MyLog;
import cxm.proj.xtalk.smack.Call;
import cxm.proj.xtalk.smack.CallManager;
import cxm.proj.xtalk.smack.CallManager.CallManagerNotify;
import cxm.proj.xtalk.smack.GroupManager;
import cxm.proj.xtalk.smack.UserManager;

@SuppressLint("DefaultLocale")
public class BuddyListFragment extends Fragment implements
			OnItemClickListener, CallManagerNotify, OnQueryTextListener {
	private List<RosterEntry> members = null;
    private BuddyListAdapter adapter = null;
    
    @Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
	        Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_buddy, container, false);
		
		return view;
	}
	
    /*
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_buddy);
		
		this.setTitle(UserManager.getInstance().getUser().getName());
		MyLog.Log(MyLog.Level.Info, "BuddyList onCreate()");
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
		// create search bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.searchview_in_menu, menu);
        // MenuItem searchItem = menu.findItem(R.id.action_search);
        // SearchView mSearchView = (SearchView)MenuItemCompat.getActionView(searchItem);
        SearchView mSearchView = (SearchView)menu.findItem(R.id.action_search).getActionView();

        if (null != mSearchView)
	        mSearchView.setOnQueryTextListener(this);
        else
        	MyLog.Log(MyLog.Level.Error, "Cannot find search view");
        return super.onCreateOptionsMenu(menu);
    }
	*/
	
	@Override
	public void onResume() {
		super.onResume();
		MyLog.Log(MyLog.Level.Info, "BuddyList onResume()");
		
		// get members
	    this.members = GroupManager.getInstance().getPublicGroup().getMembers();

	    // create list view
	    ListView list = (ListView)this.getActivity().findViewById(R.id.MyListView);  
	    this.adapter = new BuddyListAdapter(this.members);
	    list.setAdapter(adapter);
	    list.setOnItemClickListener(this);
	    
	    /*
		// listen  incomming call
		try {
			CallManager.getInstance().setCallNotify(this);
			CallManager.getInstance().listen(true);
		} catch (Exception e) {
			MyLog.Log(MyLog.Level.Error, "cannot start call manager listen");
		}
		*/
	}

	/*
	@Override
	protected void onPause() {
		super.onPause();
		MyLog.Log(MyLog.Level.Info, "BuddyList onPause()");

		try {
			CallManager.getInstance().listen(false);
			CallManager.getInstance().removeCallNotify(this);
		} catch (Exception e) {
			MyLog.Log(MyLog.Level.Error, "cannot stop call manager listen");
		}
	}
	*/
	
	/* // do not logout after return
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	    if (keyCode == KeyEvent.KEYCODE_BACK) {
			try {
				UserManager.getInstance().Release();
			} catch (Exception e) {
				MyLog.Log(MyLog.Level.Error, "Cannot logout " + e);
			}
	    }
	    return super.onKeyDown(keyCode, event);
	}
	*/
	
	private class BuddyListAdapter extends ArrayAdapter<RosterEntry> {
		private List<RosterEntry> buddyList = null;
		private List<RosterEntry> showList = null;
		private Filter filter = null;

		public BuddyListAdapter(List<RosterEntry> list) {
			super(BuddyListFragment.this.getActivity(),
					R.layout.layout_buddy_listitem, list);
			
			this.buddyList = new ArrayList<RosterEntry>();
			this.buddyList.addAll(list);
			this.showList = new ArrayList<RosterEntry>();
			this.showList.addAll(list);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			if (convertView == null) {
				LayoutInflater vi = (LayoutInflater)this.getContext().getSystemService(
						Context.LAYOUT_INFLATER_SERVICE);
				convertView = vi.inflate(R.layout.layout_buddy_listitem, null);
			}
			
			TextView textName = (TextView)convertView.findViewById(R.id.buddylist_text_name);
			textName.setText(this.showList.get(position).getName());

			return convertView;
		}
		
		@Override
		public Filter getFilter() {
			if (null == this.filter)
				this.filter = new ListFilter();
			return this.filter;
		}
		
		private class ListFilter extends Filter {
			@Override
			protected FilterResults performFiltering(CharSequence constraint) {
				FilterResults filterResults = new FilterResults();
				String filterString = "";
				if (null != constraint)
					filterString = constraint.toString().toLowerCase();
				
				// add result
				showList = new ArrayList<RosterEntry>();
				if (filterString.length() > 0) {
					int size = buddyList.size();
					for (int i = 0; i < size; i++) {
						if (buddyList.get(i).getName().contains(filterString))
							showList.add(buddyList.get(i));
					}
				} else 
					showList.addAll(buddyList);

				filterResults.values = showList;
				filterResults.count = showList.size();
				
				return filterResults;
			}

			@Override
			protected void publishResults(CharSequence arg0,
					FilterResults arg1) {
				BuddyListAdapter.this.notifyDataSetChanged();
				BuddyListAdapter.this.clear();
				for (int i = 0; i < showList.size(); i++)
					add(showList.get(i));
				BuddyListAdapter.this.notifyDataSetInvalidated();
			}
		}
	}
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		MyLog.Log(MyLog.Level.Debug, "Click item " + members.get(arg2).getName());

		try {
			CallManager.getInstance().callTo(UserManager.getJidByUserName(members.get(arg2).getName()));
		} catch (Exception e) {
			MyLog.Log(MyLog.Level.Error, "Cannot call to " + members.get(arg2).getName());
			Toast.makeText(this.getActivity(), "Cannot hold on a call ", Toast.LENGTH_LONG).show();
			return;
		}

		// start call intent to make a call
		Intent intent = new Intent(BuddyListFragment.this.getActivity(),
				CallActivity.class);
		startActivity(intent);
	}

	@Override
	public void onCall(Call call) {
		// start call intent
		Intent intent = new Intent(BuddyListFragment.this.getActivity(),
				CallActivity.class);
		startActivity(intent);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		MyLog.Log(MyLog.Level.Info, "BuddyList onDestroy()");
	}

	@Override
	public boolean onQueryTextChange(String arg0) {
		MyLog.Log(MyLog.Level.Info, "Query text changed to " + arg0);
		this.adapter.getFilter().filter(arg0);
		return false;
	}

	@Override
	public boolean onQueryTextSubmit(String arg0) {
		MyLog.Log(MyLog.Level.Info, "Query text submit to " + arg0);
		return false;
	}
}
